<template xmlns:el-col="http://www.w3.org/1999/html">
    <div class="app-container">
        <h4 class="form-header h4">基本信息</h4>
        <el-form ref="form" label-width="100px">
            <el-row>
                <el-col :span="8" :xs="24">
                    <el-form-item label="模块名称" prop="nickName">
                        <el-input v-model="moduleInfo.name" disabled/>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-row>
            <right-toolbar @queryTable="getList"></right-toolbar>
        </el-row>
        <el-row :gutter="20" v-loading="globalLoading" v-show="list.length>0">
            <el-col :span="12" :xs="24" v-for="(item,index) in list" style="margin-top: 10px">
                <el-card shadow="always">
                    <div slot="header" class="clearfix">
                        <span style="margin-right: 10px;">{{ item.name }}</span>
                        <!--                        <el-button-->
                        <!--                            plain-->
                        <!--                            size="mini"-->
                        <!--                        >批量启动-->
                        <!--                        </el-button>-->
                        <el-button
                            plain
                            size="mini"
                            :disabled="item.multiple"
                            @click="batchRead(item,index)"
                        >批量读取
                        </el-button>
                        <!--                        <el-button-->
                        <!--                            plain-->
                        <!--                            size="mini"-->
                        <!--                        >批量设置-->
                        <!--                        </el-button>-->
                        <!--                        <el-switch-->
                        <!--                            active-color="#13ce66"-->
                        <!--                            :active-value="1"-->
                        <!--                            :inactive-value="0"-->
                        <!--                            style="float: right; padding: 3px 0"-->
                        <!--                        >-->
                        <!--                        </el-switch>-->
                    </div>
                    <el-table :data="item.addressList" height="400"
                              ref="addressTable"
                              @selection-change="v=>{handleSelectionChange(v,index)}"
                    >
                        <el-table-column type="selection" width="55" align="center"/>
                        <el-table-column label="地址名称" prop="addressName" align="center"></el-table-column>
<!--                        <el-table-column label="属性" prop="property" align="center">-->
<!--                            <template v-slot="scope">-->
<!--                                <div v-show="scope.row.attribute==='0'">-->
<!--                                    <el-tag type="success">可读</el-tag>-->
<!--                                </div>-->
<!--                                <div v-show="scope.row.attribute==='1'">-->
<!--                                    <el-tag type="success">可写</el-tag>-->
<!--                                </div>-->
<!--                                <div v-show="scope.row.attribute==='0,1'">-->
<!--                                    <el-tag type="success">可读</el-tag>-->
<!--                                    <el-tag type="success" style="margin-left: 5px">可写</el-tag>-->
<!--                                </div>-->
<!--                            </template>-->
<!--                        </el-table-column>-->
                        <el-table-column label="当前值" align="center" prop="addressValue">
                            <template v-slot="scope">
                                <el-input v-model="scope.row.addressValue" v-show="scope.row.attribute==='1'"/>
                                <el-input v-model="scope.row.addressValue" v-show="scope.row.attribute==='0,1'"/>
                                <el-input v-model="scope.row.addressValue" v-show="scope.row.attribute==='0'" readonly/>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                            <template slot-scope="scope">
                                <el-button
                                    size="mini"
                                    type="text"
                                    :loading="scope.row.readLoading"
                                    v-if="scope.row.attribute==='0,1' || scope.row.attribute==='0'"
                                    @click="handleOperation(scope.row, scope.$index,'0',index)"
                                >{{ scope.row.readText }}
                                </el-button>
                                <el-button
                                    size="mini"
                                    type="text"
                                    :loading="scope.row.writeLoading"
                                    v-if="scope.row.attribute==='0,1' || scope.row.attribute==='1'"
                                    @click="handleOperation(scope.row, scope.$index,'1',index)"
                                >{{ scope.row.writeText }}
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
            </el-col>
        </el-row>

        <el-row v-loading="globalLoading" v-show="list.length===0">
            <el-col :span="24">
                <el-empty description="暂无施肥机设备"></el-empty>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import gatewaySelect from '@/views/common/GatewaySelect.vue'
import {
    getFertilizerDistributorV1,
    listFertilizerDistributorV1Module
} from '@/api/module/fertilizerDistributorV1'
import { sendMessage, sendMultipleMessage } from '@/api/netty/nettyMessage'
import current from 'element-ui/packages/table/src/store/current'

export default {
    computed: {
        current() {
            return current
        }
    },
    components: { gatewaySelect },
    name: 'index',
    data() {
        return {
            // 非多个禁用
            multiple: true,
            currentIdx: 0,
            fertilizerList: [],
            itemIndex: null,
            list: [],
            queryParams: {
                gatewayNumber: null,
                fertilizerObj: {
                    id: null
                }
                // pageNum: 1,
                // pageSize: 10,
            },
            ids: [],
            globalLoading: true,
            messageObj: {
                instruction: '10',
                paramType: '0'
            },
            gatewayListOption: [],
            messageList: [],
            moduleInfo: {},
            webClientId: this.genUUID(10, 16)

        }
    },
    destroyed() {
        if (this.ws !== undefined) {
            this.ws.close()
            // 离开页面清空倒计时
            this.list.forEach(i => {
                if (i.addressList !== null) {
                    i.addressList.forEach(item => {
                        clearInterval(item.timerRead)
                        clearInterval(item.timerWrite)
                    })
                }
            })
        }
    },
    created() {
        const moduleId = this.$route.params && this.$route.params.moduleId
        if (moduleId) {
            this.moduleId = moduleId
            this.getList()
            this.getModuleInfo()
        }
    },
    methods: {
        getList() {
            this.changeFertilizer()
        },
        getModuleInfo() {
            getFertilizerDistributorV1(this.moduleId).then(response => {
                this.moduleInfo = response.data
            })
        },
        changeFertilizer() {
            this.queryParams.fertilizerObj.id = this.moduleId
            this.globalLoading = true
            listFertilizerDistributorV1Module(this.queryParams.fertilizerObj).then(res => {
                this.list = res.data
                for (let i of this.list) {
                    i.multiple = true
                    i.currentIdx = null
                    if (i.addressList !== null) {
                        i.addressList.forEach(item => {
                            // 判断写入还是读取方式
                            item.operationType = ''
                            // 写入和读取的加载动画
                            item.readLoading = false
                            item.writeLoading = false
                            // 写入和读取的文本控制
                            item.readText = '读取'
                            item.writeText = '写入'
                            // 写入和读取的倒计时时间
                            item.readSecond = 0
                            item.writeSecond = 0
                            // 写入和读取倒计时返回值
                            item.timerRead = null
                            item.timerWrite = null
                            // 超时判断
                            item.overReadTime = true
                            item.overWriteTime = true
                        })
                    }
                }
                this.globalLoading = false
            })
        },
        handleSelectionChange(selection, index) {
            console.log(selection)
            this.list[index].multiple = !selection.length
            this.list[index].currentIdx = index
            this.list[index].ids = selection.map(item => item.id)
            this.$set(this.list, index, this.list[index])
        },
        batchRead(rowData, index) {
            this.messageList = []
            // console.log( this.list)
            // console.log('当前点击的批量读取的索引', this.list[index].currentIdx)
            this.list.forEach(item => {
                console.log('item', item)
                if (item.currentIdx === index) {
                    item.ids.forEach(id => {
                        let d = item.addressList.find((i) => {
                            return i.id === id
                        })
                        let idx = item.addressList.indexOf(d)
                        this.$set(this.list[index].addressList, idx, d)
                        let obj = {
                            gatewayId: this.moduleInfo.gatewayId,
                            id,
                            webClientId: this.webClientId,
                            instruction: '10',
                            paramType: '0',
                            operationType: '0',
                            data: {
                                moduleId: this.moduleId,
                                index: idx,
                                itemIndex: index,
                                value: d['addressValue']
                            }
                        }
                        this.messageList.push(obj)
                    })
                }
            })
            console.log(this.messageList)
            sendMultipleMessage(this.messageList).then(response => {
                if (response.code === 200) {
                    // 成功后建立websocket
                    let obj = {
                        'webClientId': this.webClientId
                    }
                    this.sendMessage(obj)
                }
            }, error => {

            })

            // console.log(this.$refs.addressTable.clearSelection())
        },
        handleOperation(row, index, operationType, itemIndex) {
            // console.log('读取', row)
            let data = this.list[itemIndex].addressList[index]
            data['operationType'] = operationType
            if ('0' === operationType) {
                data['readLoading'] = true
                data['readText'] = 30 + 's'
                data['readSecond'] = 29
            }
            if ('1' === operationType) {
                data['writeLoading'] = true
                data['writeText'] = 30 + 's'
                data['writeSecond'] = 29
            }
            this.getTimer(data, index, operationType, itemIndex)
            this.$set(this.list[itemIndex].addressList, index, data)
            this.messageObj.gatewayId = this.moduleInfo.gatewayId
            this.messageObj.id = row.id
            this.messageObj.operationType = operationType
            this.messageObj.webClientId = this.webClientId
            this.messageObj.data = {
                moduleId: this.moduleId,
                index,
                value: row.addressValue,
                itemIndex
            }
            // console.log(this.messageObj)
            this.messageObj.writeValue = row.addressValue
            this.send2Web(index, itemIndex)
        },
        // 获取超时倒计时
        getTimer(rowData, index, operationType, itemIndex) {
            // 读取
            if ('0' === operationType) {
                rowData.timerRead = setInterval(() => {
                    if (rowData.readSecond > 0) {
                        rowData.readText = rowData.readSecond + 's'
                        this.$set(this.list[itemIndex].addressList, index, rowData)
                        --rowData.readSecond
                    } else {
                        clearInterval(rowData.timerRead)
                        if (rowData.overReadTime) {
                            this.$message.info('读取超时')
                        }
                        rowData.readLoading = false
                        rowData.readText = '读取'
                        this.$set(this.list[itemIndex].addressList, index, rowData)
                    }
                }, 1000)
            }
            // 写入
            if ('1' === operationType) {
                rowData.timerWrite = setInterval(() => {
                    if (rowData.writeSecond > 0) {
                        rowData.writeText = rowData.writeSecond + 's'
                        this.$set(this.list[itemIndex].addressList, index, rowData)
                        --rowData.writeSecond
                    } else {
                        clearInterval(rowData.timerWrite)
                        rowData.writeLoading = false
                        if (rowData.overWriteTime) {
                            this.$message.info('写入超时')
                        }
                        rowData.writeText = '写入'
                        this.$set(this.list[itemIndex].addressList, index, rowData)
                    }
                }, 1000)
            }
        },
        send2Web(index, itemIndex) {
            let rowData = this.list[itemIndex].addressList[index]
            sendMessage(this.messageObj).then(response => {
                if (response.code === 200) {
                    // 成功后建立websocket
                    let obj = {
                        'webClientId': this.webClientId,
                        'type': 'login'
                    }
                    this.sendMessage(obj)
                }
            }, error => {
                // this.reset()
                if (rowData.operationType === '0') {
                    rowData.overReadTime = false
                    rowData.readSecond = 0
                    rowData.readLoading = false
                }
                if (rowData.operationType === '1') {
                    rowData.writeSecond = 0
                    rowData.overWriteTime = false
                    rowData.writeLoading = false
                }
                this.$set(this.list[itemIndex].addressList, index, rowData)
            })
        },
        // websocket 发送消息给服务器
        sendMessage(obj) {
            if (this.ws !== undefined && this.ws.readyState === 1) {
                // console.log('已存在')
                // this.$websocket.sendMsg(obj)
            } else {
                this.localSocket(obj)
            }
        },
        localSocket(obj) {
            let that = this
            if ('WebSocket' in window) {
                // console.log('您的浏览器支持 WebSocket')
                // console.log('that.ws', that.ws)
                if (that.ws !== undefined && that.ws.readyState === 1) {
                    // console.log('存在连接')
                    return
                }
                that.ws = new WebSocket(that.$websocket.url)
                that.$websocket.setWs(that.ws)
                that.ws.onopen = function() {
                    // console.log('开始连接')
                    // that.sendMessage(obj)
                    that.$websocket.sendMsg(obj)
                }
                // websocket 接收服务器消息
                that.ws.onmessage = function(result) {
                    console.log('收到websocket回复', result)
                    // console.log('回复data', result.data)
                    that.processData(result.data)
                }
                that.ws.onclose = function() {
                    // 防链接超时，（websocket在一定时间内没有数据交互，就会断开），关闭后重启
                    console.log('连接已关闭')
                    that.ws.close()
                    // setTimeout(() => {
                    //     that.localSocket()
                    // }, 2000)
                }
            } else {
                // 浏览器不支持 WebSocket
                console.log('您的浏览器不支持 WebSocket!')
            }
        },
        resetLoading(data, itemIndex) {
            let index = data['index']
            if (index !== undefined) {
                let value = data['value']
                let d = this.list[itemIndex].addressList[index]
                d['addressValue'] = value
                this.$set(this.list[itemIndex].addressList, index, d)
            }
        },
        processData(json) {
            // console.log('json', json)

            let data = {}
            try {
                data = JSON.parse(json)
            } catch (e) {
            }
            console.log('data', data)
            let webClientId = data['webClientId']
            if (webClientId === undefined) {
                return
            }
            // this.resetLoading(data, itemIndex)
            let cause = data['cause']

            // console.log('回复的webClientId', webClientId)
            let index = data['index']
            let itemIndex = data['itemIndex']
            let rowData = this.list[itemIndex].addressList[index]
            if (webClientId === this.webClientId) {
                if (cause !== undefined) {
                    this.$message.error(cause)
                    if (rowData.operationType === '0') {
                        rowData.overReadTime = false
                        rowData.readSecond = 0
                        rowData.readLoading = false
                    }
                    if (rowData.operationType === '1') {
                        rowData.writeSecond = 0
                        rowData.overWriteTime = false
                        rowData.writeLoading = false
                    }
                } else {
                    this.$message.success('成功')
                    if (rowData.operationType === '0') {
                        // console.log('读取成功')
                        rowData.overReadTime = false
                        rowData.readSecond = 0
                        rowData.readLoading = false
                        rowData.addressValue = data['value']
                    }
                    if (rowData.operationType === '1') {
                        // console.log('写入成功')
                        rowData.writeSecond = 0
                        rowData.overWriteTime = false
                        rowData.writeLoading = false
                        rowData.addressValue = data['writeValue']
                    }
                }
                console.log(this.list[itemIndex].addressList)
                this.$set(this.list[itemIndex].addressList, index, rowData)
            }
        }
    }

}
</script>

<style scoped>

</style>
